<!DOCTYPE html>
<html lang="zh-CN" layout:decorate="~{layout}">
<head>
    <title>测试管理 - HTTP性能测试工具</title>
</head>
<body>
    <div layout:fragment="content" class="container-fluid">
        <!-- 页面头部 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2><i class="fas fa-play-circle"></i> 测试管理</h2>
                <p class="text-muted mb-0">管理和监控性能测试会话</p>
            </div>
            <div class="btn-group" role="group">
                <button type="button" class="btn btn-outline-primary" onclick="refreshTestList()">
                    <i class="fas fa-sync"></i> 刷新
                </button>
                <button type="button" class="btn btn-primary" onclick="startNewTest()">
                    <i class="fas fa-plus"></i> 新建测试
                </button>
            </div>
        </div>

        <!-- 搜索和筛选 -->
        <div class="card mb-4">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" class="form-control" id="search-input" placeholder="搜索测试名称...">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <select class="form-select" id="status-filter">
                            <option value="">全部状态</option>
                            <option value="RUNNING">运行中</option>
                            <option value="COMPLETED">已完成</option>
                            <option value="FAILED">失败</option>
                            <option value="CANCELLED">已取消</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <select class="form-select" id="time-filter">
                            <option value="">全部时间</option>
                            <option value="today">今天</option>
                            <option value="week">最近一周</option>
                            <option value="month">最近一月</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-outline-secondary w-100" onclick="applyFilters()">
                            <i class="fas fa-filter"></i> 筛选
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 测试会话列表 -->
        <div class="row" id="tests-container">
            <!-- 动态加载的测试会话卡片将在这里显示 -->
        </div>

        <!-- 空状态提示 -->
        <div id="no-tests" class="text-center text-muted py-5 d-none">
            <i class="fas fa-flask fa-3x mb-3"></i>
            <h4>暂无测试会话</h4>
            <p>点击右上角"新建测试"按钮开始您的第一个性能测试</p>
            <button type="button" class="btn btn-primary" onclick="startNewTest()">
                <i class="fas fa-plus"></i> 新建测试
            </button>
        </div>

        <!-- 加载中状态 -->
        <div id="loading" class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-3 text-muted">正在加载测试会话...</p>
        </div>

        <!-- 测试详情模态框 -->
        <div class="modal fade" id="testDetailModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">测试会话详情</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div id="test-detail-content">
                            <!-- 测试详情将在这里显示 -->
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" id="view-report-btn" onclick="viewReport()">
                            <i class="fas fa-chart-bar"></i> 查看报告
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 配置选择模态框 -->
        <div class="modal fade" id="configSelectModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">选择测试配置</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="config-select" class="form-label">选择要执行的配置：</label>
                            <select class="form-select" id="config-select">
                                <option value="">请选择配置...</option>
                            </select>
                        </div>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i>
                            选择一个已保存的配置来启动新的测试会话
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="executeSelectedConfig()">
                            <i class="fas fa-play"></i> 开始测试
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <th:block layout:fragment="scripts">
        <script>
            let currentTestDetail = null;
            let refreshInterval = null;

            $(document).ready(function() {
                loadTestList();
                loadConfigOptions();
                
                // 设置自动刷新（每30秒）
                refreshInterval = setInterval(function() {
                    if (!$('#testDetailModal').hasClass('show')) {
                        loadTestList();
                    }
                }, 30000);
                
                // 搜索框回车事件
                $('#search-input').on('keypress', function(e) {
                    if (e.which === 13) {
                        applyFilters();
                    }
                });
            });

            // 页面卸载时清除定时器
            $(window).on('beforeunload', function() {
                if (refreshInterval) {
                    clearInterval(refreshInterval);
                }
            });

            function loadTestList() {
                $('#loading').show();
                $('#tests-container').empty();
                $('#no-tests').hide();
                
                $.get('/api/tests')
                    .done(function(tests) {
                        $('#loading').hide();
                        
                        if (tests.length === 0) {
                            $('#no-tests').show();
                            return;
                        }
                        
                        tests.forEach(test => {
                            createTestCard(test);
                        });
                    })
                    .fail(function() {
                        $('#loading').hide();
                        AppUtils.showError('加载测试列表失败');
                    });
            }

            function createTestCard(test) {
                const statusClass = getStatusClass(test.status);
                const statusIcon = getStatusIcon(test.status);
                const progressWidth = test.progress || 0;
                
                const cardHtml = `
                    <div class="col-md-6 col-lg-4 mb-4">
                        <div class="card h-100">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h6 class="mb-0">${escapeHtml(test.testName || '未命名测试')}</h6>
                                <span class="badge ${statusClass}">${statusIcon} ${getStatusText(test.status)}</span>
                            </div>
                            <div class="card-body">
                                <p class="text-muted mb-3">${escapeHtml(test.description || '无描述')}</p>
                                
                                <div class="row mb-3">
                                    <div class="col-6">
                                        <small class="text-muted">配置ID</small>
                                        <div>${escapeHtml(test.configId || 'N/A')}</div>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted">会话ID</small>
                                        <div>${escapeHtml(test.sessionId)}</div>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <small class="text-muted">开始时间</small>
                                    <div>${formatDateTime(test.startTime)}</div>
                                </div>
                                
                                ${test.status === 'RUNNING' ? `
                                    <div class="mb-3">
                                        <div class="d-flex justify-content-between align-items-center mb-1">
                                            <small class="text-muted">进度</small>
                                            <small>${progressWidth}%</small>
                                        </div>
                                        <div class="progress">
                                            <div class="progress-bar" role="progressbar" style="width: ${progressWidth}%"></div>
                                        </div>
                                    </div>
                                ` : ''}
                                
                                ${test.endTime ? `
                                    <div class="mb-3">
                                        <small class="text-muted">结束时间</small>
                                        <div>${formatDateTime(test.endTime)}</div>
                                    </div>
                                ` : ''}
                                
                                ${test.totalRequests ? `
                                    <div class="row mb-3">
                                        <div class="col-6">
                                            <small class="text-muted">总请求数</small>
                                            <div>${AppUtils.formatNumber(test.totalRequests)}</div>
                                        </div>
                                        <div class="col-6">
                                            <small class="text-muted">成功率</small>
                                            <div>${((test.successRequests / test.totalRequests) * 100).toFixed(1)}%</div>
                                        </div>
                                    </div>
                                ` : ''}
                            </div>
                            <div class="card-footer">
                                <div class="btn-group w-100" role="group">
                                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="viewTestDetail('${test.sessionId}')">
                                        <i class="fas fa-info-circle"></i> 详情
                                    </button>
                                    ${test.status === 'RUNNING' ? `
                                        <button type="button" class="btn btn-outline-warning btn-sm" onclick="stopTest('${test.sessionId}')">
                                            <i class="fas fa-stop"></i> 停止
                                        </button>
                                        <button type="button" class="btn btn-outline-success btn-sm" onclick="monitorTest('${test.sessionId}')">
                                            <i class="fas fa-eye"></i> 监控
                                        </button>
                                    ` : `
                                        ${test.status === 'COMPLETED' ? `
                                            <button type="button" class="btn btn-outline-success btn-sm" onclick="viewReport('${test.sessionId}')">
                                                <i class="fas fa-chart-bar"></i> 报告
                                            </button>
                                        ` : ''}
                                        <button type="button" class="btn btn-outline-danger btn-sm" onclick="deleteTest('${test.sessionId}')">
                                            <i class="fas fa-trash"></i> 删除
                                        </button>
                                    `}
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                
                $('#tests-container').append(cardHtml);
            }

            function getStatusClass(status) {
                switch (status) {
                    case 'RUNNING': return 'bg-primary';
                    case 'COMPLETED': return 'bg-success';
                    case 'FAILED': return 'bg-danger';
                    case 'CANCELLED': return 'bg-warning';
                    default: return 'bg-secondary';
                }
            }

            function getStatusIcon(status) {
                switch (status) {
                    case 'RUNNING': return '<i class="fas fa-spinner fa-spin"></i>';
                    case 'COMPLETED': return '<i class="fas fa-check"></i>';
                    case 'FAILED': return '<i class="fas fa-times"></i>';
                    case 'CANCELLED': return '<i class="fas fa-ban"></i>';
                    default: return '<i class="fas fa-question"></i>';
                }
            }

            function getStatusText(status) {
                switch (status) {
                    case 'RUNNING': return '运行中';
                    case 'COMPLETED': return '已完成';
                    case 'FAILED': return '失败';
                    case 'CANCELLED': return '已取消';
                    default: return '未知';
                }
            }

            function formatDateTime(timestamp) {
                if (!timestamp) return 'N/A';
                return new Date(timestamp).toLocaleString('zh-CN');
            }

            function refreshTestList() {
                loadTestList();
                AppUtils.showSuccess('测试列表已刷新');
            }

            function applyFilters() {
                const searchTerm = $('#search-input').val().toLowerCase();
                const statusFilter = $('#status-filter').val();
                const timeFilter = $('#time-filter').val();
                
                $('#tests-container .col-md-6').each(function() {
                    const $card = $(this);
                    const testName = $card.find('.card-header h6').text().toLowerCase();
                    const status = $card.find('.badge').text().trim();
                    
                    let visible = true;
                    
                    // 搜索过滤
                    if (searchTerm && !testName.includes(searchTerm)) {
                        visible = false;
                    }
                    
                    // 状态过滤
                    if (statusFilter && !status.includes(getStatusText(statusFilter))) {
                        visible = false;
                    }
                    
                    // 时间过滤（简化实现）
                    if (timeFilter) {
                        // 这里可以根据实际需求实现时间过滤逻辑
                    }
                    
                    $card.toggle(visible);
                });
            }

            function viewTestDetail(sessionId) {
                $.get(`/api/tests/${sessionId}`)
                    .done(function(test) {
                        currentTestDetail = test;
                        showTestDetailModal(test);
                    })
                    .fail(function() {
                        AppUtils.showError('加载测试详情失败');
                    });
            }

            function showTestDetailModal(test) {
                const detailHtml = `
                    <div class="row">
                        <div class="col-md-6">
                            <h6>基本信息</h6>
                            <table class="table table-sm">
                                <tr>
                                    <td>测试名称</td>
                                    <td>${escapeHtml(test.testName || 'N/A')}</td>
                                </tr>
                                <tr>
                                    <td>会话ID</td>
                                    <td>${escapeHtml(test.sessionId)}</td>
                                </tr>
                                <tr>
                                    <td>配置ID</td>
                                    <td>${escapeHtml(test.configId || 'N/A')}</td>
                                </tr>
                                <tr>
                                    <td>状态</td>
                                    <td><span class="badge ${getStatusClass(test.status)}">${getStatusText(test.status)}</span></td>
                                </tr>
                                <tr>
                                    <td>开始时间</td>
                                    <td>${formatDateTime(test.startTime)}</td>
                                </tr>
                                <tr>
                                    <td>结束时间</td>
                                    <td>${formatDateTime(test.endTime)}</td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h6>统计信息</h6>
                            <table class="table table-sm">
                                <tr>
                                    <td>总请求数</td>
                                    <td>${AppUtils.formatNumber(test.totalRequests || 0)}</td>
                                </tr>
                                <tr>
                                    <td>成功请求</td>
                                    <td>${AppUtils.formatNumber(test.successRequests || 0)}</td>
                                </tr>
                                <tr>
                                    <td>失败请求</td>
                                    <td>${AppUtils.formatNumber((test.totalRequests || 0) - (test.successRequests || 0))}</td>
                                </tr>
                                <tr>
                                    <td>成功率</td>
                                    <td>${test.totalRequests ? ((test.successRequests / test.totalRequests) * 100).toFixed(2) : 0}%</td>
                                </tr>
                                <tr>
                                    <td>平均响应时间</td>
                                    <td>${AppUtils.formatDuration(test.avgResponseTime || 0)}</td>
                                </tr>
                                <tr>
                                    <td>QPS</td>
                                    <td>${(test.requestsPerSecond || 0).toFixed(2)}</td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    ${test.errorMessage ? `
                        <div class="mt-3">
                            <h6>错误信息</h6>
                            <div class="alert alert-danger">
                                ${escapeHtml(test.errorMessage)}
                            </div>
                        </div>
                    ` : ''}
                `;
                
                $('#test-detail-content').html(detailHtml);
                $('#view-report-btn').toggle(test.status === 'COMPLETED');
                new bootstrap.Modal(document.getElementById('testDetailModal')).show();
            }

            function stopTest(sessionId) {
                if (!confirm('确定要停止这个测试吗？')) return;
                
                $.ajax({
                    url: `/api/tests/${sessionId}/stop`,
                    method: 'POST'
                })
                .done(function(response) {
                    if (response.success) {
                        AppUtils.showSuccess('测试已停止');
                        loadTestList();
                    } else {
                        AppUtils.showError(response.message || '停止测试失败');
                    }
                });
            }

            function deleteTest(sessionId) {
                if (!confirm('确定要删除这个测试会话吗？此操作不可恢复。')) return;
                
                $.ajax({
                    url: `/api/tests/${sessionId}`,
                    method: 'DELETE'
                })
                .done(function(response) {
                    if (response.success) {
                        AppUtils.showSuccess('测试会话已删除');
                        loadTestList();
                    } else {
                        AppUtils.showError(response.message || '删除测试失败');
                    }
                });
            }

            function monitorTest(sessionId) {
                window.location.href = `/tests/${sessionId}/monitor`;
            }

            function viewReport(sessionId) {
                if (currentTestDetail) {
                    sessionId = currentTestDetail.sessionId;
                }
                window.location.href = `/reports/${sessionId}`;
            }

            function startNewTest() {
                new bootstrap.Modal(document.getElementById('configSelectModal')).show();
            }

            function loadConfigOptions() {
                $.get('/api/configs')
                    .done(function(configs) {
                        const select = $('#config-select');
                        select.empty().append('<option value="">请选择配置...</option>');
                        
                        configs.forEach(config => {
                            select.append(`<option value="${config.id}">${escapeHtml(config.name)}</option>`);
                        });
                    });
            }

            function executeSelectedConfig() {
                const configId = $('#config-select').val();
                if (!configId) {
                    AppUtils.showError('请先选择配置');
                    return;
                }
                
                $.ajax({
                    url: '/api/tests/start',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ configId: configId })
                })
                .done(function(response) {
                    if (response.success) {
                        AppUtils.showSuccess('测试启动成功');
                        bootstrap.Modal.getInstance(document.getElementById('configSelectModal')).hide();
                        loadTestList();
                        
                        // 跳转到监控页面
                        setTimeout(() => {
                            window.location.href = `/tests/${response.sessionId}/monitor`;
                        }, 1000);
                    } else {
                        AppUtils.showError(response.message || '启动测试失败');
                    }
                });
            }

            function escapeHtml(text) {
                if (!text) return '';
                const div = document.createElement('div');
                div.textContent = text;
                return div.innerHTML;
            }
        </script>
    </th:block>
</html>